/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package botoseis.mainGui.temp;

import botoseis.mainGui.utils.Allow;
import java.awt.event.ActionEvent;
import java.util.TimerTask;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Timer;
import botoseis.mainGui.utils.Utils;
import botoseis.mainGui.workflows.WorkflowJob;
import botoseis.mainGui.utils.RendererTable;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author wogonowski
 */
public class JobList extends javax.swing.JFrame {

    /**
     * Creates new form JobList
     */
    public JobList() {
        super("Job List");
        initComponents();
        jobsTable.getTableHeader().setFont(new Font("Arial",Font.BOLD,12));
        // Display window on position
        Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        setPreferredSize(new Dimension(1024, 260));
        Dimension windowSize = new Dimension(getPreferredSize());
        int wdwLeft = (screenSize.width / 2)- (windowSize.width / 2);
        int wdwTop =(screenSize.height / 2)+ ((screenSize.height / 2) - windowSize.height-24) ;
        setLocation(wdwLeft, wdwTop); 
       Action action = new AbstractAction("Update jobs") {
          public void actionPerformed(ActionEvent e) {
               updateJobsTable(m_ProjectLine);
            }
        };
        Timer timer = new Timer(3000, action);
        timer.start();
        jobsTable.setDefaultRenderer(Object.class, new RendererTable());
        setVisible(true);
        // For checking open window
         Allow.allow_ = false;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        m_processOutput = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jobsTable = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnView = new javax.swing.JButton();
        btnRun = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnRemove = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        m_consoleAreas = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jobsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Flow Name", "Project / Line", "Status", "Start", "End", "Duration", "Processed (MB)", ""
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, false, false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jobsTable.setSelectionBackground(new java.awt.Color(255, 245, 185));
        jobsTable.setSelectionForeground(new java.awt.Color(255, 245, 185));
        jobsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jobsTable);
        jobsTable.getColumnModel().getColumn(1).setPreferredWidth(115);
        jobsTable.getColumnModel().getColumn(2).setPreferredWidth(30);
        jobsTable.getColumnModel().getColumn(6).setPreferredWidth(28);
        jobsTable.getColumnModel().getColumn(7).setMinWidth(0);
        jobsTable.getColumnModel().getColumn(7).setPreferredWidth(0);
        jobsTable.getColumnModel().getColumn(7).setMaxWidth(0);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        btnView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/botoseis/pics/Information16.png"))); // NOI18N
        btnView.setToolTipText("Show output");
        btnView.setFocusable(false);
        btnView.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnView.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewActionPerformed(evt);
            }
        });
        jToolBar1.add(btnView);

        btnRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/botoseis/pics/Play16.png"))); // NOI18N
        btnRun.setToolTipText("Execute selected job");
        btnRun.setFocusable(false);
        btnRun.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRun.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRun);

        btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/botoseis/pics/Stop16.png"))); // NOI18N
        btnStop.setToolTipText("Stop select job");
        btnStop.setFocusable(false);
        btnStop.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnStop.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopActionPerformed(evt);
            }
        });
        jToolBar1.add(btnStop);
        jToolBar1.add(jSeparator1);

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/botoseis/pics/Remove16.png"))); // NOI18N
        btnRemove.setToolTipText("Remove selected item from table");
        btnRemove.setFocusable(false);
        btnRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRemove);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 964, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane1.getAccessibleContext().setAccessibleParent(jPanel1);

        m_processOutput.addTab("Job History", jPanel2);
        jPanel2.getAccessibleContext().setAccessibleParent(jPanel1);

        m_consoleAreas.setColumns(20);
        m_consoleAreas.setRows(5);
        jScrollPane3.setViewportView(m_consoleAreas);

        m_processOutput.addTab("Console", jScrollPane3);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(m_processOutput)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(m_processOutput)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    public void addJob(WorkflowJob njob,javax.swing.JTextArea console,String m_ProjectLine) {
           if(this.getExtendedState() == JobList.ICONIFIED) { 
            this.setVisible(true);
            this.setExtendedState(NORMAL);
            } else {
             this.setVisible(true);
             this.toFront();
             this.requestFocus();    
        m_jobsList.add(njob);
        // Display info on console tab
        m_consoleAreas.append(console.getText()+"---------- END ----------\n");
        updateJobsTable(m_ProjectLine);
 
   }
 //if(this.getExtendedState() == JobsList.MAXIMIZED_BOTH) { // do stuff }   
    }

    private void updateJobsTable(String m_ProjectLine) {
        for (int i = 0; i < MAX_ROWS; i++) {
            jobsTable.setValueAt("", i, 0);
            jobsTable.setValueAt("", i, 1);
            jobsTable.setValueAt("", i, 2);
            jobsTable.setValueAt("", i, 3);
        }

        String title;
        for (int i = 0; i < m_jobsList.size(); i++) {
            title = m_jobsList.get(i).getTitle();
            String user = System.getProperty("user.name");
            String path = m_jobsList.get(i).getHomeDir();

            jobsTable.setValueAt(title, i, 0);
//            jobsTable.setValueAt(user + " - " + path, i, 1);
            jobsTable.setValueAt(m_jobsList.get(i).getProjectLine(), i, 1);
            jobsTable.setValueAt(m_jobsList.get(i).getStatus(), i, 2);
            jobsTable.setValueAt(Utils.getDateFormated(m_jobsList.get(i).getTimeStart()), i, 3);
            jobsTable.setValueAt(Utils.getDateFormated(m_jobsList.get(i).getTimeStop()), i, 4);
            jobsTable.setValueAt(m_jobsList.get(i).getDuration(), i, 5);
            jobsTable.setValueAt(m_jobsList.get(i).getProcessed(), i, 6);
            jobsTable.setValueAt(i, i, 7);
        }
    }

    private void btnViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewActionPerformed
        int row = jobsTable.getSelectedRow();
        if (row >= 0) {
            m_jobsList.get(row).getFlowLog().setVisible(true);
            //        java.io.File logf = m_jobsList.get(row).getLogfile();
            //        WorkflowLogDlg dlg = new WorkflowLogDlg(null, false);
            //        dlg.loadFile(logf);
            //
            //        dlg.setVisible(true);

        }
    }//GEN-LAST:event_btnViewActionPerformed

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunActionPerformed
        int row = jobsTable.getSelectedRow();
        if (row >= 0) {
            m_jobsList.get(row).getFlowLog().loadFromFile(null);
            m_jobsList.get(row).start();
        }

    }//GEN-LAST:event_btnRunActionPerformed

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
        int row = jobsTable.getSelectedRow();
        if (row >= 0) {
            m_jobsList.get(new Integer(jobsTable.getValueAt(row, 7).toString())).stop();
        }
    }//GEN-LAST:event_btnStopActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        int row = jobsTable.getSelectedRow();
        if (row >= 0) {
            if (!jobsTable.getValueAt(row, 7).toString().equals("")) {
                java.io.File hd = new java.io.File(m_jobsList.get((Integer.parseInt(jobsTable.getValueAt(row, 7).toString()))).getHomeDir());

                int ans = javax.swing.JOptionPane.showConfirmDialog(this, "The folder :" + hd.toString()
                    + "\nwill be permanently removed!", "User folder removal", javax.swing.JOptionPane.OK_CANCEL_OPTION);
                if (ans == javax.swing.JOptionPane.OK_OPTION) {
                    Utils.deleteFile(hd);
                    int id = Integer.parseInt(jobsTable.getValueAt(row, 7).toString());
                    for (int i = 0; i < jobsTable.getColumnCount(); i++) {
                        jobsTable.setValueAt("", row, i);
                    }
                    m_jobsList.remove(id);
                    jobsTable.updateUI();

                }
            }

        }
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        Allow.allow_ = true;
        this.setVisible(false);
        //this.dispose();
       // setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                    
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JobList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JobList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JobList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JobList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JobList().setVisible(true);
           }
            
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnRun;
    private javax.swing.JButton btnStop;
    private javax.swing.JButton btnView;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable jobsTable;
    private javax.swing.JTextArea m_consoleAreas;
    private javax.swing.JTabbedPane m_processOutput;
    // End of variables declaration//GEN-END:variables
    private java.util.Vector<WorkflowJob> m_jobsList = new java.util.Vector<WorkflowJob>();
    private int MAX_ROWS = 50;
    private String m_ProjectLine;

}
